package beautiful.butterfly.distributed_task_processing_engine.tools;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Timestamp<=>yyyy-MM-dd HH:mm:ss
 */
public class TimestampJsonSerializerAndJsonDeserializer implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp>
{
    public JsonElement serialize(Timestamp timestamp, Type type, JsonSerializationContext jsonSerializationContext)
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String string = dateFormat.format(new Date(timestamp.getTime()));
        return new JsonPrimitive(string);
    }

    public Timestamp deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException
    {
        if (!(jsonElement instanceof JsonPrimitive))
        {
            throw new JsonParseException("The date should be a string value");
        }

        try
        {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = dateFormat.parse(jsonElement.getAsString());
            return new Timestamp(date.getTime());
        } catch (Exception e)
        {
            throw new JsonParseException(e);
        }
    }

}
